import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 
 * @author Matt
 * GRIP Send Server class
 */

public class GRIPSendServer extends Thread {

	private Point pos;
	private int port;
	private PGPeer peer;
	private ServerSocket welcomeSocket = null;
	private int delay = 30000;
	
	GRIPSendServer(Point pos, PGPeer peer, int port){
		this.pos = pos;
		this.port = port;
		this.peer = peer;
	}
	
	public void shutdown(){
		if(welcomeSocket != null)
			try {
				welcomeSocket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	public void run(){
		try {
			PSPUtil.print("GRIP Send server " + pos + "start...listening on port " + port, false);
			welcomeSocket = new ServerSocket(port);
			
			while(true){
				
				//Socket connectionSocket = welcomeSocket.accept();
				Socket connectionSocket = new Socket("localhost", port);
				Socket tempSocket = gSocket.connectTo(this.pos);
				
				//System.out.println(connectionSocket.getPort() + " " + tempSocket.getPort());
				
				PSPUtil.print("GRIP Send thread start...", peer.getPrint());
				
				GRIPSendThread thread = new GRIPSendThread(connectionSocket, peer, pos);				
				thread.start();					
				PSPUtil.print("GRIP Send thread end...", peer.getPrint());				
				Thread.sleep(delay);
				
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
